package algorithm;

import java.util.HashMap;
import java.util.Map;

public class T00567 {
    public static void main(String[] args) {
        String s1 = "ab";
        String s2 = "eidbaooo";
        System.out.println(new Solution().checkInclusion(s1, s2));
    }

    static class Solution {
        public boolean checkInclusion(String s1, String s2) {
            if (s1.length() > s2.length()) return false;
            Map<Character, Integer> window = new HashMap<>();
            Map<Character, Integer> need = new HashMap<>();
            int valid = 0, len1 = s1.length();
            for (int i = 0; i < s1.length(); i ++) {
                char c = s1.charAt(i);
                need.put(c, need.getOrDefault(c, 0) + 1);
                char d = s2.charAt(i);
                window.put(d, window.getOrDefault(d, 0) + 1);
                if (window.get(d).equals(need.get(d))) {
                    valid ++;
                }
            }
            if (valid == len1) return true;
            for (int i = s1.length(); i < s2.length(); i ++) {
                char c = s2.charAt(i);
                window.put(c, window.getOrDefault(c, 0) + 1);
                if (window.get(c).equals(need.get(c))) {
                    valid ++;
                }
                char d = s2.charAt(i - len1);
                window.put(d, window.get(d) - 1);
                if (window.get(d).equals(need.get(d))) {
                    valid --;
                }
                if (valid == len1) return true;
            }
            return false;
        }
    }
}
